﻿#include "stdafx.h"
#include "NewGen.h"
#include "ClassInstanceType.h"
#include "modules.h"

using namespace llvm;
llvm::Value * NewGen::generateCode(llvm::Module *m, llvm::Function *func, llvm::IRBuilder<>&builder)
{
	if (_value) return _value;
	Function* createObject = CLangModule::getFunction("createObject");
	assert(createObject);

	Type* ty = type->llvmType(createObject->getContext());
	Constant* AllocSize = ConstantExpr::getSizeOf(ty);
	auto *x=AllocSize->getType();

	auto ITy = Type::getInt32Ty(m->getContext());
	AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, ITy);

	Value* typeId=ConstantInt::get(ITy, type->typeId());

	std::vector<Value*> args;
	args.push_back(AllocSize);
	args.push_back(typeId);

	if (length) {	  // 是数组
		auto v=length->generateCode(m, func, builder);
		auto a = ConstantExpr::getTruncOrBitCast(AllocSize, ITy);
		args.push_back(a);
		_value = builder.CreateCall(createObject, args, "createArray");
	}
	else {
		_value = builder.CreateCall(createObject, args, "createObject");
	}
	auto *pType = PointerType::get(ty, 0);
	_value = builder.CreateBitCast(_value, pType);

	// 调用构造函数
	if (construstor) construstor->generateCode(m, func, builder);

	//auto *c = _type->constructor;
	//if (c) {
	//	std::vector<Value*> a;
	//	a.push_back(v);
	//	c->generateCall(builder, a);
	//}

	std::string n = ty->getStructName();
	n[0] = tolower(n[0]);
	_value->setName(n);
	return _value;
}
